/* 
 * File:   LogSystem.cpp
 * Author: Gab'z
 * 
 * Created on 2 mai 2012, 23:21
 */

#include "LogSystem.h"
#include "LogMessage.h"
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <sstream> 

using namespace std;

namespace calculator {

    std::string LogSystem::destination = "calculatrice.log";
    int LogSystem::TRACE = 0;
    int LogSystem::DEBUG = 1;
    int LogSystem::ERROR = 2;

    LogSystem::LogSystem() {
    }

    LogSystem::~LogSystem() {
        LoggerManager::deleteInstance();
    }

    void LogSystem::log(const LogMessage& message) {
        std::string level;
        switch (message.getLevel()) {
            case 0: level = "TRACE";
                break;
            case 1: level = "DEBUG";
                break;
            case 2: level = "ERROR";
                break;
        }

        std::ostringstream oss;

        time_t now = time(0);
        tm *ltm = localtime(&now);
        oss << ltm->tm_year + 1900 << "-";
        oss << ltm->tm_mon + 1 << "-";
        oss << ltm->tm_mday << " ";
        oss << ltm->tm_hour << ":";
        oss << ltm->tm_min << ":";
        oss << ltm->tm_sec << " ";
        oss << level << " ";
        oss << message.getClassname() << " ";
        oss << message.getMessage() << std::endl;

        std::string m = oss.str();
        if (message.getLevel() == 2) {
            logErrorToConsole(m);
        } else {
            logToConsole(m);
        }
        logToFile(m);
    }

    void LogSystem::logToFile(const std::string& message) {
        ofstream fichier(destination.c_str(), ios::out | ios::app);
        if (!fichier.fail()) {
            fichier << message;
            fichier.close();
        } else cerr << "Impossible d'ouvrir le fichier !" << endl;
    }

    void LogSystem::logToConsole(const std::string& message) {
        std::cout << message;
        std::cout.flush();
    }

    void LogSystem::logErrorToConsole(const std::string& message) {
        std::cerr << message;
        std::cerr.flush();
    }

}